import axios from 'axios'
import store from '@/store/index'
import api_config from "../../config/api_config"


const host = api_config.host
const port = api_config.port
const schema = api_config.schema

/* 普通请求 */
let conf = {
  baseURL: `${schema}://${host}:${port}`
  // baseURL: "/"
}
// console.log("conf", conf)
const axiosCustom = axios.create(conf)

/* 普通请求 */
export const request = (method, url, params = {}, data = {}, config = {}, autoErrorRes = true, autoErrorData = true, autoCancel = true) => {
  if (autoCancel) {
    config = Object.assign({ cancelToken: store.state.source.token }, config)
  }
  const args = Object.assign({
    'method': method,
    'url': url,
    'params': params,
    'data': data
  }, config)

  return axiosCustom(args).then((res) => {
    // 自动处理返回格式错误
    if (autoErrorData && res.data.hasOwnProperty('code') && res.data.code !== "SUCCESS") {
      const errMsg = res.data.message || '未知的服务器错误，请联系管理员！'
      const errCod = res.data.code
      console.log(errMsg,  errCod)
    }
    return res.data
  }, (error) => {
    // 自动处理网络请求错误
    error.response = error.response || {}
    const errStatus = error.response.status || -100
    if (autoErrorRes && error.message) {
      console.log('网络请求异常，请联系管理员！', '请求异常：' + errStatus)
    }
  })
}

/* 静态资源请求 */
let staticConf = {
  baseURL: "/"
}
const axiosCustomStatic = axios.create(staticConf)
export const requestStatic = (url) => {
  const args = {
    'method': "GET",
    'url': url,
  }

  return axiosCustomStatic(args).then((res) =>{
    return res.data
  }, (error) => {
    error.response = error.response || {}
    const errStatus = error.response.status || -100
    if (autoErrorRes && error.message) {
      console.log('网络请求异常，请联系管理员！', '请求异常：' + errStatus, { confirmButtonText: '确定' })
    }
    return Promise.reject(error)})
}